/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.pig4cloud.pig.goods.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.goods.entity.TbItem;
import com.pig4cloud.pig.goods.service.TbItemService;
import com.pig4cloud.pig.goods.utils.QiniuCloudUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.common.unit.Fuzziness;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import java.util.*;


/**
 * 商品表
 *
 * @author pig code generator
 * @date 2021-07-15 18:55:25
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/tbitem" )
@Api(value = "tbitem", tags = "商品表管理")
public class TbItemController {


	@Autowired
	private UploadController uploadController;

	@Autowired
    private final  TbItemService tbItemService;

	@Autowired
	RestHighLevelClient esRestClient;

    /**
     * 分页查询
     * @param page 分页对象
     * @param tbItem 商品表
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('goods_tbitem_get')" )
    public R getTbItemPage(Page page, TbItem tbItem) throws IOException {
		//            构建搜索请求
		SearchRequest hetong = new SearchRequest("pinyougoudb");
		//            构造一个搜索生成器
		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
		QueryBuilder boolQueryBuilder = null;
		if(tbItem.getTitle()!=null&&!tbItem.getTitle().equals("")){
			boolQueryBuilder = QueryBuilders.matchQuery("title",tbItem.getTitle()).fuzziness(Fuzziness.AUTO);
		}else {
			boolQueryBuilder = QueryBuilders.matchAllQuery();
		}
		searchSourceBuilder.query(boolQueryBuilder);
		long current = page.getCurrent();
		searchSourceBuilder.from(Integer.valueOf(String.valueOf((current-1)*page.getSize())));
		searchSourceBuilder.size(Integer.valueOf(String.valueOf(page.getSize())));
//            创建高亮生成器
		HighlightBuilder highlightBuilder = new HighlightBuilder();
//            高亮的字段
		highlightBuilder.field("title");
//            高亮前缀
		highlightBuilder.preTags("<span style='color: red'>");
//            高亮后缀
		highlightBuilder.postTags("</span>");
//            是否多个字段高亮
		highlightBuilder.requireFieldMatch(true);
//            添加到搜索生成其中
		searchSourceBuilder.highlighter(highlightBuilder);
//            将搜索生成添加到搜索请求
		hetong.source(searchSourceBuilder);
		SearchResponse search = esRestClient.search(hetong, RequestOptions.DEFAULT);
		System.err.println(search);
//            获取搜索到的信息
		SearchHit[] hits = search.getHits().getHits();
		ArrayList<Map<String, Object>> objects = new ArrayList<>();
		for (SearchHit hit : hits) {
			Map<String, HighlightField> highlightFields = hit.getHighlightFields();
			HighlightField tenantName = highlightFields.get("title");
			Map<String, Object> sourceAsMap = hit.getSourceAsMap();
			if(tenantName!=null){
				Text[] fragments = tenantName.fragments();
				String title = "";
				for (Text fragment : fragments) {
					title += fragment;
				}
				sourceAsMap.put("title",title);
			}

			objects.add(sourceAsMap);
		}
		objects.forEach(a->{
			System.err.println(a);
		});
		System.err.println();
		TotalHits b = search.getHits().getTotalHits();
		Integer total = Integer.valueOf(String.valueOf(b.value));
		return R.ok(objects).setTotal(total);
    }

	/**
	 * 分页查询
	 * @param page 分页对象
	 * @param tbItem 商品表
	 * @return
	 */
	@ApiOperation(value = "买家商品列表", notes = "买家商品列表")
	@GetMapping("/page_consumer" )
	public List consumerList(Page page, TbItem tbItem) {
		return tbItemService.ConsumerList();
	}

	/**
	 * 分页查询
	 * @param page 分页对象
	 * @param tbItem 商品表
	 * @return
	 */
	@ApiOperation(value = "秒杀商品列表", notes = "秒杀")
	@GetMapping("/page_consumer_miaosha")
	public List consumerList_miaosha(Page page, TbItem tbItem) {
		return tbItemService.ConsumerListMiaosha();
	}


    /**
     * 通过id查询商品表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('goods_tbitem_get')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(tbItemService.getById(id));
    }

    /**
     * 新增商品表
     * @param tbItem 商品表
     * @return R
     */
    @ApiOperation(value = "新增和修改商品表", notes = "新增或修改")
    @SysLog("新增或修改" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('goods_tbitem_add')" )
    public Boolean uploadImg(@RequestBody TbItem tbItem) {
    	/*判断id不等空,走添加的方法*/
    	if(tbItem.getId()!=null){
			boolean b = tbItemService.updateById(tbItem);
			return b;
		}else{
    		/*如果id是空，就走添加的方法*/
			tbItem.setImage("http://"+tbItem.getImage());
			Boolean b = tbItemService.save(tbItem);
			return b;
		}
	}

	/**
	 * 新增图片
	 * @return R
	 */
	/*@ApiOperation(value = "上传图片", notes = "图片")
	@SysLog("上传图片" )
	@PostMapping("uploadImg")
	public String uploadImg(MultipartFile image, HttpServletRequest request) throws IOException {
		String s = uploadController.uploadImg(image, request);
//		String s = QiniuCloudUtil.upload(image.getOriginalFilename(),image.getName());
		return s;
	}*/

	@ResponseBody
	@RequestMapping(value="/uploadImg", method= RequestMethod.POST)
	public String uploadImg(@RequestBody MultipartFile file, HttpServletRequest request) {
		if (file!=null&&file.isEmpty()) {
			return "文件为空，请重新上传";
		}
		try {
			byte[] bytes = file.getBytes();
			String imageName = UUID.randomUUID().toString();

			QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
			try {
				//使用base64方式上传到七牛云
				String url = qiniuUtil.put64image(bytes, imageName);
				System.out.println(url);
				return url;
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "啥都没有";
		} catch (IOException e) {

			return "出异常了";
		}
	}

    /**
     * 修改商品表
     * @param tbItem 商品表
     * @return R
     *//*
    @ApiOperation(value = "修改商品表", notes = "修改商品表")
    @SysLog("修改商品表" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('goods_tbitem_edit')" )
    public R updateById(@RequestBody TbItem tbItem) {
        return R.ok(tbItemService.updateById(tbItem));
    }*/

    /**
     * 通过id删除商品表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除商品表", notes = "通过id删除商品表")
    @SysLog("通过id删除商品表" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('goods_tbitem_del')" )
    public R removeById(@PathVariable Long id) {
        return R.ok(tbItemService.removeById(id));
    }

}
